package com.rivulet.foreign.config;

import com.rivulet.foreign.pojo.User;
import com.rivulet.foreign.service.UserService;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

import static com.rivulet.foreign.tools.Status.*;

/**
 * {登录验证的逻辑实现}
 *
 * @author xujiac
 * @create 2021/7/19
 * @since 1.0.0
 */
public class LoginRealm extends AuthorizingRealm {
    @Autowired
    UserService userService;

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        return null;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        String user_id = (String) authenticationToken.getPrincipal();
        String password = String.valueOf(authenticationToken.getCredentials());
        Integer identity = Integer.valueOf(authenticationToken.toString());
        User user = new User(user_id, password, identity);
        String results = userService.loginService(user);
        if (results.equals(ERROR)) {
            throw new UnknownAccountException();
        }
        if (results.equals(BAD_ERROR)||results.equals(EXCEPTION)) {
            throw new IncorrectCredentialsException();
        }
        return new SimpleAuthenticationInfo(user_id, password, getName());
    }
}
